# Copyright (c) 2022, hzmes and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document
from frappe.model.mapper import get_mapped_doc
# from frappe.desk.form.load import get_attachments
from frappe.utils import (
	add_to_date, getdate, today
)

class SRMSampleRequest(Document):

	def autoname(self):
		if self.naming_series:
			self.name = self.naming_series

	def before_insert(self):
		if not self.naming_series:
			current_naming_series = "YPSQ-"
			current_naming_series += "".join(today().split("-"))
			series = frappe.db.get_value('SRM Naming Series',
								{'doctype_name': self.doctype, 'date': today()},
								['name', 'current_series'], as_dict=True)
			if series:
				current_naming_series += str(series.current_series).zfill(3)
			else:
				frappe.get_doc({'doctype': 'SRM Naming Series', 'doctype_name': self.doctype, 'date': today()}).insert(ignore_permissions=True)
				current_naming_series += "001"
			self.naming_series = current_naming_series
			frappe.db.set_value('SRM Naming Series', series.name, 'current_series', series.current_series + 1)

	
	# 定义一个日期计算方法以内部调用
	@frappe.whitelist()
	def calc_date(self, date_from, days, as_string=True, as_datetime=True):
		return add_to_date(date_from, days=int(days))

	
	@frappe.whitelist()
	def send_supplier_emails(self, rev_email):
		if rev_email:
			# rev_email.append('iou198298@163.com')
			# rev_email.append('115259901@163.com')
			rev_email.append(self.purchaser)
			docname = self.name
			sample_name = self.sample_category_purchase
			# 2023-11-19优化: 规格型号中会有换行符需要替换为<br>
			sample_model = self.sample_model.replace('\n', '<br>')
			technical_requirement =self.technical_requirement
			purchaser = self.purchaser if self.purchaser else frappe.get_doc("User", frappe.session.user).username
			purchaser_name = self.purchaser_name if self.purchaser_name else frappe.session.user
			notes_of_purchase = self.notes_of_purchase
			return_date = self.return_date
			element_qty_2 = self.element_qty_2
			email_note = self.email_note
			# 2023-08-07优化: "样品承认"为"是"的，就发送"本次样品需进行物料承认，样品和纸档承认书请一起提供"
			msg = "本次样品需进行物料承认,样品和纸档承认书请一起提供" if self.sample_state == "是" else ""
			if self.sample_file:
				cur_attachments = self.get_attachments()
				get_subject = f"{self.material_company_name}- 打样资料通知-有附件 - {docname} - {sample_model}"
				# if not isinstance(get_subject,unicode):
				# 	get_subject = unicode(get_subject)
				frappe.sendmail(
					recipients=rev_email,
					sender=frappe.session.user,
					attachments=cur_attachments,
					reference_doctype=self.doctype,
					reference_name=docname,
					subject=get_subject,
					message=f"<p style='color:red;'> 本邮件属于系统发送-有附件，请勿直接回复 </p><p style='color:red;'> {msg} </p><br><p> 样品申请单号: {docname}</p><br><p> 样品名称: {sample_name}</p><br><p> 规格型号: {sample_model}</p><br><p> 技术要求: {technical_requirement}</p><br><p> 采购备注: {notes_of_purchase}</p><br><p> 交期: {return_date}</p><br><p> 数量: {element_qty_2}</p><br><p>{email_note}</p><br><p> 如不能按期交付，请尽早回复。</p><br><p> 联系人: {purchaser_name}</p><br><p> 联系方式: {purchaser}</p><br>",
				)
			else:
				get_subject = f"{self.material_company_name}- 打样资料通知-无附件 - {docname} - {sample_model}"
				# if not isinstance(get_subject,unicode):
				# 	get_subject = unicode(get_subject)
				frappe.sendmail(
					recipients=rev_email,
					sender=frappe.session.user,
					reference_doctype=self.doctype,
					reference_name=docname,
					subject=get_subject,
					message=f"<p style='color:red;'> 本邮件属于系统发送-无附件，请勿直接回复 </p><p style='color:red;'> {msg} </p><br><p> 样品申请单号: {docname}</p><br><p> 样品名称: {sample_name}</p><br><p> 规格型号: {sample_model}</p><br><p> 技术要求: {technical_requirement}</p><br><p> 采购备注: {notes_of_purchase}</p><br><p> 交期: {return_date}</p><br><p> 数量: {element_qty_2}</p><br><p>{email_note}</p><br><p> 如不能按期交付，请尽早回复。</p><br><p> 联系人: {purchaser_name}</p><br><p> 联系方式: {purchaser}</p><br>",
				)
			
			self.admit_closed = 1
			self.save()
			self.reload()


	# 批量更新字段,以dict传递
	@frappe.whitelist()
	def field_update(self, dict):
		for key, value in dict.items():
			if key in self.as_dict().keys():
				frappe.db.set_value(self.doctype, self.name, key, value)
		self.reload()


	@frappe.whitelist()
	def get_filed_descrition(self, doctype, name):
		return frappe.get_doc(doctype, name)

	
	def get_attachments(self):
		#通过当前单据及对就的上传字段名获取已上传文件名称/编号
		fname = frappe.db.get_value('File',
			{
				"attached_to_name": self.name,
				"attached_to_doctype": self.doctype,
				# "attached_to_field": "sample_file"
			})
		#获取文件单据对象
		file_doc = frappe.get_doc('File', fname)
		#填充发邮件时的附件参数，主要是获取pdf文件二进制内容
		attachments=[{"fname": file_doc.file_name,"fcontent": file_doc.get_content()}]

		# 2023-03-14 发送所有附件
		# file_names = frappe.db.get_list('File',filters = {"attached_to_name": self.name,"attached_to_doctype": self.doctype})
		# attachments = []
		# for f in file_names:
		# 	file_doc = frappe.get_doc('File', f.name)
		# 	attachments.append({"fname": file_doc.file_name, "fcontent": file_doc.get_content()})
		return attachments


# 生成承认单
@frappe.whitelist()
def make_sample_admit(source_name, supplier):
	doc = frappe.get_doc({
		"doctype": "SRM Sample Admit",
		"rcbillno": source_name,
		"supplier": supplier
	})
	doc.submission_user = frappe.session.user
	doc.insert()
	frappe.db.commit()
	return doc


# 标准列表查询时，不同角色强行限制查询条件
def get_permission_query_conditions(user):
	roles = []
	for r in frappe.get_doc('User', user).roles:
		roles.append(r.role)
	# frappe.msgprint(roles)
	if ('System Manager' in roles):
		return ""
	elif ('SRM Purchase Manager' in roles):
		return """(`tabSRM Sample Request`.workflow_state not in ('Save'))"""
	elif ('SRM Big Leader' in roles):
		return """(`tabSRM Sample Request`.workflow_state in ('Be Received'))"""